/*
 *
 *  Copyright (C) 2008-2010 GSyC/LibreSoft, Universidad Rey Juan Carlos
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see http://www.gnu.org/licenses/.
 *
 *  Author : Roberto Calvo Palomino <rocapal@libresoft.es>
 *
 */

package com.LibreGeoSocial.App;

import java.lang.reflect.Method;
import java.util.Hashtable;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;

import com.LibreGeoSocial.Api.Audio;
import com.LibreGeoSocial.Api.GeoNode;
import com.LibreGeoSocial.Api.LibreGeoSocial;
import com.LibreGeoSocial.Api.Note;
import com.LibreGeoSocial.Api.Photo;
import com.LibreGeoSocial.Api.User;
import com.LibreGeoSocial.Api.Layers.GenericLayer;
import com.LibreGeoSocial.Api.Layers.LibreGeoSocialLayer;
import com.LibreGeoSocial.Api.Layers.NodeListLayer;
import com.LibreGeoSocial.Api.Layers.PanoramioLayer;
import com.LibreGeoSocial.Api.Layers._11870Layer;
import com.LibreGeoSocial.App.AR.ARView;
import com.LibreGeoSocial.App.AlarmManager.AlarmService;
import com.LibreGeoSocial.App.AlarmManager.NodeAlarm;
import com.LibreGeoSocial.App.Content.ContentCreation;
import com.LibreGeoSocial.App.Content.ContentUpload;
import com.LibreGeoSocial.App.Maps.ResourcesMap;
import com.LibreGeoSocial.App.Routes.LocationService;
import com.LibreGeoSocial.App.Utils.LocationUtils;

public class NodeList extends GenericList implements OnClickListener {

	private static final int MENU_SEARCH = Menu.FIRST + 10;
	private static final int MENU_DISTANCE = Menu.FIRST + 11;
	private static final int MENU_DISTANCE_0 = Menu.FIRST + 12;
	private static final int MENU_DISTANCE_1 = Menu.FIRST + 13;
	private static final int MENU_DISTANCE_5 = Menu.FIRST + 14;
	private static final int MENU_DISTANCE_10 = Menu.FIRST + 15;
	private static final int MENU_DISTANCE_50 = Menu.FIRST + 16;
	private static final int MENU_SEE_CAM = Menu.FIRST + 17;
	private static final int MENU_FILTER = Menu.FIRST + 18;
	private static final int MENU_ALARM_NODE = Menu.FIRST + 19;
	private static final int MENU_PRIVACY = Menu.FIRST + 20;
	private static final int MENU_LOCATION_PRIVACY = Menu.FIRST + 21;
	private static final int MENU_DELETE = Menu.FIRST + 22;
	private static final int MENU_SEE_MAP = Menu.FIRST + 23;

	private static final int DIALOG_SEARCH = 10;
	private static final int DIALOG_FILTER = 11;
	private static final int DIALOG_CREATE_ALARM = 12;
	private static final int DIALOG_PRIVACY = 13;
	private static final int DIALOG_LOCATION_PRIVACY = 14;
	private static final int DIALOG_NO_RESULTS = 15;

	public static final String LGS_RESOURCE = "lgs_resource";

	private NodeAdapter mAdapter = null;
	private Thread th = null;

	private static GenericLayer mylayer = null;

	private String[] strCategories = null;

	private Boolean isLGSLayer = false;

	private String mPrivacy = null;

	private ContentUpload contentUpload;
	private ContentCreation contentCreation;

	private static Bitmap layerBitmap;

	private Button prevButton;
	private Button nextButton;

	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);

		// Get the layer
		Intent i = getIntent();
		mylayer = (GenericLayer) i.getSerializableExtra("layer");

		// Reset pagination
		mylayer.resetPagination();

		// Get Icon of the layer
		layerBitmap = mylayer.getIcon();

		// Adding generic menus for content
		if (LibreGeoSocialLayer.class.isInstance(mylayer)) {
			contentUpload = new ContentUpload(this);
			contentUpload.setResourceLocation(LocationService
					.getCurrentLocation());

			contentCreation = new ContentCreation(this);
		}

		/* Initialize the categories */
		if (strCategories == null) {
			if (mylayer.getCategories() != null) {
				strCategories = mylayer.getCategories().clone();
				for (int j = 0; j < strCategories.length; j++)
					strCategories[j] = "0";
			}
		}

		// Buttons to navigate
		prevButton = (Button) this.findViewById(R.id.btPrev);
		prevButton.setOnClickListener(this);

		nextButton = (Button) this.findViewById(R.id.btNext);
		nextButton.setOnClickListener(this);

		if (mNodeList == null || mNodeList.isEmpty())
			updateResources();
		else {
			setAdapter();
		}
	}

	public void onClick(View v) {

		if (prevButton.isPressed() && mylayer.getCurrentPage()==1)
		{
			Toast.makeText(getBaseContext(),
						"First Page. No previous results!", 
						Toast.LENGTH_LONG).show();
		}
		else
		{
			if (prevButton.isPressed()) 
			{
				mylayer.previousPage();
				
			} else if (nextButton.isPressed()) 
			{
				mylayer.nextPage();
			}
	
			updateResources();
		}

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if ((mNodeList != null) && (keyCode == KeyEvent.KEYCODE_BACK))
			mNodeList.clear();

		DataManager.getInstance().removeData(DataManager.GENERIC_LAYER);
		DataManager.getInstance().removeData(DataManager.LAYER_CATEGORIES);

		return super.onKeyDown(keyCode, event);
	}

	private void updateResources() {
		/* 11870 Layer */

		if (_11870Layer.class.isInstance(mylayer)) {
			_11870Layer layer2 = (_11870Layer) mylayer;
			th = layer2.getThreadtoUpdate(handler_Adapter, strCategories);

			showProgressDialog("Downloading", "Downloading 11870 layer...", th);

		} else if (LibreGeoSocialLayer.class.isInstance(mylayer)) {
			LibreGeoSocialLayer layer = (LibreGeoSocialLayer) mylayer;
			th = layer.getThreadtoUpdate(handler_Adapter, strCategories);

			isLGSLayer = true;

			showProgressDialog("Downloading",
					"Downloading LibreGeoSocial layer...", th);

		} else if (NodeListLayer.class.isInstance(mylayer)) {
			NodeListLayer layer = (NodeListLayer) mylayer;
			th = layer.getThreadtoUpdate(handler_Adapter, strCategories);

			showProgressDialog("Downloading", "Downloading Nodes ...", th);
		} else if (PanoramioLayer.class.isInstance(mylayer)) {
			PanoramioLayer layer = (PanoramioLayer) mylayer;
			th = layer.getThreadtoUpdate(handler_Adapter, strCategories);

			showProgressDialog("Downloading",
					"Downloading Panoramio layer ...", th);
		} else
			Log.e("NodeList:", "Sorry, I don't know this type of layer!");

	}

	private Handler handler_Adapter = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (isFinishing())
				return;
			initAdapter();
		}
	};

	private void setAdapter() {
		if (mAdapter == null) {
			Log.e("NodeList: size=", String.valueOf(mNodeList.size()));

			mAdapter = new NodeAdapter(this);
			setListAdapter(mAdapter);

			// Init gestures
			GesturesHandler gestureHand = new GesturesHandler();
			gestureHand.initGestures(this, R.raw.gestures);

			Hashtable<Object, Object> htGestures = new Hashtable<Object, Object>();

			try {

				/* Set the static methods that execute when gesture is recognize */
				Class c = PhotoList_LGS.class;
				Method m = c.getDeclaredMethod("GestureNext", (Class[]) null);
				Method m2 = c.getDeclaredMethod("GesturePrevious",
						(Class[]) null);

				htGestures.put((Object) "Previous", m);
				htGestures.put((Object) "Next", m2);

			} catch (NoSuchMethodException e) {
				e.printStackTrace();
			}

			gestureHand.setGestures(htGestures);

		}
	}

	/**
	 * This adapter
	 */
	private void initAdapter() {
		Log.e("NodeList", "initAdapter");

		mNodeList = mylayer.getNodes();

		setAdapter();

		// Update the adapter
		mAdapter.notifyDataSetChanged();

		// Stop the thread
		th.stop();

		// Send message to close the progressDialog
		handler_PDialog.sendEmptyMessage(0);

		if (mNodeList.size()!=0)
		{
			// Show the page in the screen
			Toast.makeText(getBaseContext(),
					"Showing page " + mylayer.getCurrentPage(), 
					Toast.LENGTH_SHORT).show();
		}
		else
		{
			showDialog(DIALOG_NO_RESULTS);
		}
	}

	protected void onListItemClick(ListView l, View v, int position, long id) {

		GeoNode myNode = mNodeList.get(position);

		if (Photo.class.isInstance(myNode)) {
			Intent i = new Intent(this, PhotoCard.class);
			i.putExtra("node", myNode);

			startActivity(i);
		} else if (Note.class.isInstance(myNode)) {
			Intent i = new Intent(this, NoteCard.class);
			i.putExtra("node", myNode);

			startActivity(i);
		} else if (User.class.isInstance(myNode)) {
			Intent i = new Intent(this, UserCard.class);
			i.putExtra("node", myNode);

			startActivity(i);
		} else if (Audio.class.isInstance(myNode)) {
			Intent i = new Intent(this, AudioCard.class);
			i.putExtra("node", myNode);

			startActivity(i);
		}
		// else if ( Video.class.isInstance(myNode) )
		// {
		// Intent i = new Intent(this, VideoCard.class);
		// i.putExtra("node",myNode);
		//    
		// startActivity(i);
		// }

	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View view,
			ContextMenuInfo menuInfo) {

		super.onCreateContextMenu(menu, view, menuInfo);

		menu.add(0, MENU_ALARM_NODE, 0, "Create Alarm");

		if (isLGSLayer) {
			menu.add(0, MENU_PRIVACY, 0, "Privacy");
			menu.add(0, MENU_LOCATION_PRIVACY, 0, "Location perms");
			menu.add(0, MENU_DELETE, 0 , "Delete");
		}

	}

	public boolean onContextItemSelected(MenuItem item) {
		super.onContextItemSelected(item);

		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
				.getMenuInfo();
		mNode = (GeoNode) mNodeList.get(info.position);

		switch (item.getItemId()) {

		case MENU_ALARM_NODE:

			showDialog(DIALOG_CREATE_ALARM);
			break;

		case MENU_PRIVACY:

			showDialog(DIALOG_PRIVACY);
			break;

		case MENU_LOCATION_PRIVACY:

			showDialog(DIALOG_LOCATION_PRIVACY);
			break;
			
		case MENU_DELETE:
			
			if (Note.class.isInstance(mNode)) 
			{
				if ( LibreGeoSocial.getInstance().deleteNote(mNode.getId()) )
				{
					mNodeList.remove(info.position);
					setListAdapter(mAdapter);
				
					Toast.makeText(getBaseContext(), 
						   "Note deleted correctly!", Toast.LENGTH_LONG).show();
				}
				else
					Toast.makeText(getBaseContext(), 
							   "Error: " + LibreGeoSocial.getInstance().getLastMsgServer() , Toast.LENGTH_LONG).show();
			}
			else if (Photo.class.isInstance(mNode))
			{
				if (LibreGeoSocial.getInstance().deletePhoto(mNode.getId()) )
				{
					mNodeList.remove(info.position);
					setListAdapter(mAdapter);
				
					Toast.makeText(getBaseContext(), 
						   "Photo deleted correctly!", Toast.LENGTH_LONG).show();
				}
				else
					Toast.makeText(getBaseContext(), 
							"Error: " + LibreGeoSocial.getInstance().getLastMsgServer() , Toast.LENGTH_LONG).show();
			}
			else if (Audio.class.isInstance(mNode))
			{
				if (LibreGeoSocial.getInstance().deleteSound(mNode.getId()) )
				{
					mNodeList.remove(info.position);
					setListAdapter(mAdapter);
				
					Toast.makeText(getBaseContext(), 
						   "Sound deleted correctly!", Toast.LENGTH_LONG).show();
				}
				else
					Toast.makeText(getBaseContext(), 
							"Error: " + LibreGeoSocial.getInstance().getLastMsgServer() , Toast.LENGTH_LONG).show();
			}
			
			break;

		}

		return true;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		if (getIntent().getIntExtra("group", Integer.MIN_VALUE) == Integer.MIN_VALUE) {
			super.onCreateOptionsMenu(menu);

			menu.add(0, MENU_SEARCH, 0, "Search to ...").setIcon(
					R.drawable.search_48).setAlphabeticShortcut('A');

			if (strCategories != null)
				menu.add(0, MENU_FILTER, 0, "Filter...").setIcon(
						R.drawable.filter);

			SubMenu sub = menu.addSubMenu(0, MENU_DISTANCE, 0, "Distance")
					.setIcon(R.drawable.meter);

			sub.add(0, MENU_DISTANCE_0, 0, "500 m");
			sub.add(0, MENU_DISTANCE_1, 0, "1 Km");
			sub.add(0, MENU_DISTANCE_5, 0, "5 Km");
			sub.add(0, MENU_DISTANCE_10, 0, "10 Km");
			sub.add(0, MENU_DISTANCE_50, 0, "50 Km");

			if (contentUpload != null)
				contentUpload.onCreateOptionsMenu(menu);
			if (contentCreation != null)
				contentCreation.onCreateOptionsMenu(menu);

			menu.add(0, MENU_SEE_CAM, 0, "Show in AR").setIcon(
					R.drawable.real_view);
			menu.add(0, MENU_SEE_MAP, 0, "Show on map").setIcon(
					R.drawable.logo);

		}
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (((contentUpload == null) || !contentUpload
				.onOptionsItemSelected(item))
				&& ((contentCreation == null) || !contentCreation
						.onOptionsItemSelected(item)))
			switch (item.getItemId()) {

			case MENU_SEARCH:

				showDialog(DIALOG_SEARCH);
				break;

			case MENU_FILTER:

				showDialog(DIALOG_FILTER);
				break;

			case MENU_DISTANCE_0:

				mylayer.setDistance(0.5);
				updateResources();
				mAdapter.notifyDataSetChanged();
				break;

			case MENU_DISTANCE_1:

				mylayer.setDistance(1.0);
				updateResources();
				mAdapter.notifyDataSetChanged();
				break;

			case MENU_DISTANCE_5:

				mylayer.setDistance(5.0);
				updateResources();
				mAdapter.notifyDataSetChanged();
				break;

			case MENU_DISTANCE_10:

				mylayer.setDistance(10.0);
				updateResources();
				mAdapter.notifyDataSetChanged();
				break;

			case MENU_DISTANCE_50:

				mylayer.setDistance(50.0);
				updateResources();
				mAdapter.notifyDataSetChanged();
				break;

			case MENU_SEE_CAM:

				Intent i = new Intent(this, ARView.class);
				DataManager.getInstance().putData(DataManager.GENERIC_LAYER,
						mylayer);
				DataManager.getInstance().putData(DataManager.LAYER_CATEGORIES,
						strCategories);
				startActivity(i);
				break;
			case MENU_SEE_MAP:

				Intent i2 = new Intent(this, ResourcesMap.class);
				DataManager.getInstance().putData(DataManager.RESOURCES_LIST,
						mNodeList);
				startActivity(i2);
				break;
			}

		return super.onOptionsItemSelected(item);
	}

	protected Dialog onCreateDialog(final int id) {
		if (contentUpload != null) {
			Dialog d = contentUpload.onCreateDialog(id);
			if (d != null)
				return d;
		}

		if (contentCreation != null) {
			Dialog d = contentCreation.onCreateDialog(id);
			if (d != null)
				return d;
		}

		switch (id) {

		case DIALOG_CREATE_ALARM:

			LayoutInflater factory1 = LayoutInflater.from(this);
			final View textEntryView1 = factory1.inflate(R.layout.alarm_form,
					null);

			final EditText nameAlarm = (EditText) textEntryView1
					.findViewById(R.id.txttitle);
			final EditText distanceAlarm = (EditText) textEntryView1
					.findViewById(R.id.txtdistance);

			return new AlertDialog.Builder(this).setTitle("Create Alarm")
					.setView(textEntryView1).setPositiveButton("Ok",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {

									/* User clicked OK so do some stuff */
									NodeAlarm nAlarm = new NodeAlarm(nameAlarm
											.getText().toString(), mNode,
											Double.valueOf(distanceAlarm
													.getText().toString()));

									AlarmService.registerAlarm(nAlarm);

									Toast.makeText(getBaseContext(),
											"Create Alarm correctly!: ",
											Toast.LENGTH_LONG).show();
								}
							}).setNegativeButton("Cancel",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {

									/* User clicked cancel so do some stuff */
								}
							}).create();

		case DIALOG_SEARCH:

			LayoutInflater factory = LayoutInflater.from(this);
			final View textEntryView = factory.inflate(R.layout.search, null);

			final EditText edit = (EditText) textEntryView
					.findViewById(R.id.txtSearch);
			final TextView title = (TextView) textEntryView
					.findViewById(R.id.state_view);
			final CheckBox cbSemantic = (CheckBox) textEntryView
					.findViewById(R.id.cbSemantic);
			edit.setText("");

			return new AlertDialog.Builder(this).setTitle("Search to ...")
					.setView(textEntryView).setPositiveButton("Search",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {

									// mSemanticSearch = cbSemantic.isChecked();

									mylayer.setPattern(edit.getText()
											.toString());
									updateResources();

									mAdapter.notifyDataSetChanged();

								}
							}).setNegativeButton("cancel",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {

									/* User clicked cancel so do some stuff */
								}
							}).create();

		case DIALOG_FILTER:

			boolean[] checkItem = new boolean[mylayer.getCategories().length];
			for (int i = 0; i < checkItem.length; i++)
				checkItem[i] = true;

			return new AlertDialog.Builder(this).setTitle("Categories")
					.setMultiChoiceItems(mylayer.getCategories(), checkItem,
							new DialogInterface.OnMultiChoiceClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton, boolean isChecked) {
									/* Do whatever with checked buttons */
									Log.e("DIALOG_FILTER, whichButton = ",
											String.valueOf(whichButton));
									Log.e("DIALOG_FILTER, isChecked = ", String
											.valueOf(isChecked));

									if (isChecked)
										strCategories[whichButton] = "0";
									else
										strCategories[whichButton] = "1";

								}
							}).setPositiveButton("OK",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									/* User clicked Yes so do some stuff */
									/*
									 * Is there a way to reset the checked
									 * buttons state to false from here?
									 */

									updateResources();
								}
							}).setNegativeButton("Cancel",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									/* User clicked No so do some stuff */
									/*
									 * Is there a way to reset the checked
									 * buttons state to false from here?
									 */
								}
							}).create();

		case DIALOG_PRIVACY:
		case DIALOG_LOCATION_PRIVACY:

			return new AlertDialog.Builder(this).setTitle("Privacy")
					.setSingleChoiceItems(R.array.privacy, -1,
							new DialogInterface.OnClickListener() {

								public void onClick(DialogInterface dialog,
										int which) {

									mPrivacy = getResources().getStringArray(
											R.array.values_privacy)[which];

								}

							}).setPositiveButton("OK",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {

									if (LibreGeoSocial
											.getInstance()
											.setPrivacyNode(
													mNode.getId(),
													mPrivacy,
													id == DIALOG_LOCATION_PRIVACY)) {

										Toast.makeText(getBaseContext(),
												"Privacy changed correctly!",
												Toast.LENGTH_LONG).show();
									} else {

										Toast
												.makeText(
														getBaseContext(),
														"Error "
																+ LibreGeoSocial
																		.getInstance()
																		.getLastMsgServer(),
														Toast.LENGTH_LONG)
												.show();
									}

								}
							}).setNegativeButton("Cancel",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {

								}
							}).create();
			
			case DIALOG_NO_RESULTS:
				
				LayoutInflater factory2 = LayoutInflater.from(this);
	    		final View textEntryView2 = factory2.inflate(R.layout.custom_dialog, null);
	    		
	    		TextView text = (TextView) textEntryView2.findViewById (R.id.dialog_text);
	    		ImageView image = (ImageView) textEntryView2.findViewById(R.id.dialog_image);
	
	    		text.setText("No more results for this search!\nYou can modify the search parameters for obtain more information.");
	
	    		
		        return new AlertDialog.Builder(this)	        
		        .setTitle("No Layer Results")		        
		        .setView(textEntryView2) 
		        .setIcon(R.drawable.logo)
		        .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
		            public void onClick(DialogInterface dialog, int whichButton) {
		            	
		            	mylayer.previousPage();
		            	if (mylayer.getCurrentPage()!= 1)
		            		updateResources();
		            }
		        })
			    .create();

		}

		return super.onCreateDialog(id);

	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (contentUpload != null)
			contentUpload.onActivityResult(requestCode, resultCode, data);
	}

	public static class NodeAdapter extends BaseAdapter {

		private Context mContext;

		public NodeAdapter(Context c) {
			mContext = c;
		}

		public int getCount() {
			// TODO Auto-generated method stub
			return mNodeList.size();
		}

		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			View view;

			if (convertView == null) {
				// Make up a new view
				LayoutInflater inflater = (LayoutInflater) mContext
						.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				view = inflater.inflate(R.layout.generic_list, null);
			} else {
				// Use convertView if it is available
				view = convertView;
			}

			ImageView img = (ImageView) view.findViewById(R.id.image);

			GeoNode myResource = mNodeList.get(position);
			String title = null;
			String description = null;

			// FIXME: Refactor with other class

			// Calculate distance
			String distString = "";

			if (myResource.getLatitude() == -1.0
					&& myResource.getLongitude() == -1.0) {
				distString = "Unknow Location";
			} else if (LocationService.getCurrentLocation() == null)
				distString = "Unknow Location";
			else {
				// Calculate distance
				float dist = LocationUtils.calculateDistance(LocationService
						.getCurrentLocation(), myResource.getLocation());

				distString = LocationUtils.displayDistance(dist,
						LocationUtils.AUTO);
			}

			// Layer icon

			if (Photo.class.isInstance(myResource)) {

				Photo myphoto = (Photo) mNodeList.get(position);
				img.setImageBitmap(myphoto.getBitmapImageThumb());
				title = myphoto.getName();
				description = "Dist: " + distString + "\n"
						+ myphoto.getDescription();

			} else if (Note.class.isInstance(myResource)) {
				Note mynote = (Note) mNodeList.get(position);

				if (mylayer.getNameLayer().compareTo("11870") == 0)
					img.setImageBitmap(layerBitmap);
				else
					img.setImageResource(R.drawable.paper_pencil_70);

				title = mynote.getTitle();
				description = "Dist: " + distString + "\n" + mynote.getBody();

			} else if (User.class.isInstance(myResource)) {

				User myuser = (User) mNodeList.get(position);

				if (myuser.getAvatarId() == null)
					img.setImageResource(R.drawable.user_70);
				else
					img.setImageBitmap(myuser.getAvatarBitmap());

				title = myuser.getName() + " (" + myuser.getUsername() + ")";
				description = distString + " - " + myuser.getState();

			} else if (Audio.class.isInstance(myResource)) {
				Audio mysound = (Audio) mNodeList.get(position);
				img.setImageResource(R.drawable.audio_70);
				title = mysound.getName();
				description = "Dist: " + distString + "\n"
						+ mysound.getDescription();

			}
			// else if (Video.class.isInstance(myResource) )
			// {
			// Video myvideo = (Video) mNodeList.get(position);
			// img.setImageResource(R.drawable.audio_48);
			// title = myvideo.getName();
			// description = "Dist: " + distString + "\n" +
			// myvideo.getDescription();
			// }

			TextView t = (TextView) view.findViewById(R.id.title);
			t.setText(title);

			t = (TextView) view.findViewById(R.id.owner);
			t.setText(description);

			return view;

		}

	}

}
